import random
# from .xiuxian2_handle import UserBuffDate#, XIUXIAN_IMPART_BUFF
# from ..xiuxian_config import convert_rank
# from .utils import number_to
# changelog:
# version 0.2.0: 2024-Oct-08
# 1. 修正了PVE战斗中普攻及倍率攻击的伤害计算系数（0.75）
# 2. 修正了PVE战斗中dot技能的伤害计算
# 3. 修正了PVE战斗中伤害显示方式，改为显示税后伤害
# 4. 增加了PVE战斗开始时玩家的攻击血量buff
# 5. 增加了8层9层boss的开局随机减伤及buff、debuff数值
# version 0.1.3: 2024-Sep-20
# 1. 修复了boss战开局减伤日志
# 2. 重构部分伤害显示代码，换算大数字以增加可读性
# 3. 简化日志，仅保留
# version 0.1.1: 2024-Sep-14
# 1. 修改了玩家dot技能计算公式，dot伤害不计算boss减伤
# 2. 修改了玩家中毒辅修的计算方式，需要考虑boss的减伤


boss_zs = 0
boss_hx = 0 
boss_bs = 0
boss_jg = 0
boss_jh = 0
boss_jb = 0
boss_xx = 0
boss_xl =0

random_break = 0
random_xx = 0
random_hx = 0
random_def = 0

def calculated(self, rate: dict) -> str:
        """
        根据概率计算，轮盘型
        :rate:格式{"数据名":"获取几率"}
        :return: 数据名
        """

        get_list = []  # 概率区间存放

        n = 1
        for name, value in rate.items():  # 生成数据区间
            value_rate = int(value)
            list_rate = [_i for _i in range(n, value_rate + n)]
            get_list.append(list_rate)
            n += value_rate

        now_n = n - 1
        get_random = random.randint(1, now_n)  # 抽取随机数

        index_num = None
        for list_r in get_list:
            if get_random in list_r:  # 判断随机在那个区间
                index_num = get_list.index(list_r)
                break

        return list(rate.keys())[index_num]

def convert_rank(rank_name):
    """
    获取境界等级，替代原来的USERRANK
    convert_rank('江湖好手')[0] 返回江湖好手的境界等级
    convert_rank('江湖好手')[1] 返回境界列表
    """
    ranks = [
        '江湖好手', # 57
        '搬血境初期', '搬血境中期', '搬血境圆满',
        '洞天境初期', '洞天境中期', '洞天境圆满', # 51
        '化灵境初期', '化灵境中期', '化灵境圆满',
        '铭纹境初期', '铭纹境中期', '铭纹境圆满',
        '列阵境初期', '列阵境中期', '列阵境圆满',
        '尊者境初期', '尊者境中期', '尊者境圆满', # 39
        '神火境初期', '神火境中期', '神火境圆满',
        '真一境初期', '真一境中期', '真一境圆满',
        '圣祭境初期', '圣祭境中期', '圣祭境圆满',
        '天神境初期', '天神境中期', '天神境圆满', # 27
        '虚道境初期', '虚道境中期', '虚道境圆满',
        '斩我境初期', '斩我境中期', '斩我境圆满',
        '遁一境初期', '遁一境中期', '遁一境圆满',
        '至尊境初期', '至尊境中期', '至尊境圆满', # 15
        '真仙境初期', '真仙境中期', '真仙境圆满',
        '仙王境初期', '仙王境中期', '仙王境圆满',
        '准帝境初期', '准帝境中期', '准帝境圆满',
        '仙帝境初期', '仙帝境中期', '仙帝境圆满',
        '祭道境初期', '祭道境中期', '祭道境圆满' # 0
    ]
    
    if rank_name in ranks:
        rank_number = len(ranks) - ranks.index(rank_name) - 1
        return rank_number, ranks
    else:
        return None, ranks

def number_to(num, digits=2):
    '''
    Recursively converts a number to a string with the largest unit and specified decimal places.
    Handles scientific notation and negative numbers.
    '''
    def strofsize(num, level):
        if level >= 29:
            return num, level
        elif num >= 10000:
            num /= 10000
            level += 1
            return strofsize(num, level)
        else:
            return num, level
        
    units = ['', '万', '亿', '兆', '京', '垓', '秭', '穰', '沟', '涧', '正', '载', '极', 
             '恒河沙', '阿僧祗', '那由他', '不思议', '无量大', '万无量大', '亿无量大', 
             '兆无量大', '京无量大', '垓无量大', '秭无量大', '穰无量大', '沟无量大', 
             '涧无量大', '正无量大', '载无量大', '极无量大']
    
    # Handle scientific notation
    if "e" in str(num):
        num = float(f"{num:.{digits}f}")
    
    # Handle negative numbers
    is_negative = num < 0
    num = abs(num)
    
    num, level = strofsize(num, 0)
    
    if level >= len(units):
        level = len(units) - 1
    
    result = f"{round(num, digits)}{units[level]}"
    
    return f"-{result}" if is_negative else result


def get_st2_type():
    data_dict = ST2
    return get_dict_type_rate(data_dict)

def get_st1_type():
    """根据概率返回事件类型"""
    data_dict = ST1
    return get_dict_type_rate(data_dict)

def get_dict_type_rate(data_dict):
    """根据字典内概率,返回字典key"""
    temp_dict = {}
    for i, v in data_dict.items():
        try:
            temp_dict[i] = v["type_rate"]
        except:
            continue
    key = calculated(temp_dict)
    return key

ST1 ={
        "攻击": {
            "type_rate": 50,
        },
        "会心": {
            "type_rate": 50,
        },
        "暴伤": {
            "type_rate": 50,
        },
        "禁血": {
            "type_rate": 50,
        }
    }

ST2 ={
        "降攻": {
            "type_rate": 50,
        },
        "降会": {
            "type_rate": 50,
        },
        "降暴": {
            "type_rate": 50,
        },
        "禁蓝": {
            "type_rate": 50,
        }
    }


def Boss_fight(player1: dict, boss: dict, limit_num: int = 20):
    """
    回合制战斗
    战斗，消耗气血、真元
    数据示例：
    {"user_id": None,"道号": None, "气血": None, "攻击": None, "真元": None, '会心':None, 'exp':None}
    """
    # user1_buff_date = UserBuffDate(player1['user_id'])  # 1号的buff信息
    # if user1_buff_date is None: # 处理为空的情况
    #     user1_main_buff_data = None
    # else:
    #     user1_main_buff_data = user1_buff_date.get_user_main_buff_data()
        # user1_hp_buff = user1_main_buff_data['hpbuff'] if user1_main_buff_data is not None else 0
        # user1_mp_buff = user1_main_buff_data['mpbuff'] if user1_main_buff_data is not None else 0
    
    # 加载玩家主修功法数据
    user1_main_buff_data = {}
    if player1 is not None:
        user1_main_buff_data['name'] = player1['主功法名称']
        user1_main_buff_data['hpbuff'] = player1["主功法血量buff"]
        user1_main_buff_data['mpbuff'] = player1["主功法蓝量buff"]
        # user1_main_buff_data['atkbuff'] = player1["主功法攻击buff"]
        # user1_main_buff_data['defbuff'] = player1["主功法防御buff"]
        # user1_main_buff_data['critbuff'] = player1["主功法会心buff"]
    
    # 加载玩家传承数据
    impart_data = {}
    if player1 is not None:
        impart_data['impart_hp_per'] = player1['传承提升血']
        impart_data['impart_mp_per'] = player1['传承提升蓝']
        # impart_data['impart_atk_per'] = player1['传承提升攻']
        impart_data['impart_know_per'] = player1['传承提升会']
        impart_data['impart_burst_per'] = player1['传承提升爆']
    
    global random_break
    global random_xx
    global random_hx
    global random_def

    random_break = 0
    random_xx = 0
    random_hx = 0
    random_def = 0       
        
    user1_break = 0
    
    BOSSDEF = {
    "衣以候": "衣以侯布下了禁制镜花水月，",
    "金凰儿": "金凰儿使用了神通：金凰天火罩！",
    "九寒": "九寒使用了神通：寒冰八脉！",
    "莫女": "莫女使用了神通：圣灯启语诀！",
    "术方": "术方使用了神通：天罡咒！",
    "卫起": "卫起使用了神通：雷公铸骨！",
    "血枫": "血枫使用了神通：混世魔身！",
    "以向": "以向使用了神通：云床九练！",
    "砂鲛": "不说了！开鳖！",
    "神风王": "不说了！开鳖！",
    "鲲鹏": "鲲鹏使用了神通：逍遥游！",
    "天龙": "天龙使用了神通：真龙九变！",
    "历飞雨": "厉飞雨使用了神通：天煞震狱功！",
    "外道贩卖鬼": "不说了！开鳖！",
    "元磁道人": "元磁道人使用了法宝：元磁神山！",
    "散发着威压的尸体": "尸体周围爆发了出强烈的罡气！"
}
    
    # 加载玩家神通（技能）数据
    player1_skil_open = False
    user1_skill_date = {}
    if player1 is not None:
        # user1_skill_date = user1_buff_date.get_user_sec_buff_data()
        user1_skill_date['skill_type'] = player1['神通类型代码']
        user1_skill_date['name'] = player1['神通名称']
        user1_skill_date['atkvalue'] = player1['神通倍率数值']
        user1_skill_date['turncost'] = player1['神通持续回合数']
        user1_skill_date['rate'] = player1['神通释放概率']
        user1_skill_date['hpcost'] = player1['神通血量消耗']
        user1_skill_date['mpcost'] = player1['神通蓝量消耗']
        user1_skill_date['buffvalue'] = player1['神通buff数值']
        user1_skill_date['bufftype'] = player1['神通buff类型']
        user1_skill_date['desc'] = '骚话骚话骚话骚话'

        player1_skil_open = True

    # 加载玩家辅修功法数据
    player1_sub_open = False #辅修功法14
    user1_sub_buff_date = {}
    if player1 is not None:
        # user1_sub_buff_date = user1_buff_date.get_user_sub_buff_data()
        user1_sub_buff_date['name'] = player1['辅修名称']
        user1_sub_buff_date['buff_type'] = player1['辅修类型代码']
        user1_sub_buff_date['buff'] = player1['辅修buff数值']
        user1_sub_buff_date['buff2'] = player1['辅修buff2数值']
        player1_sub_open = True

    play_list = [] # 战斗过程数据
    if player1['气血'] != 0:
        # 根据20241008汐汐酱PVE战斗记录，血量有1.5倍buff
        player1['气血'] = int(player1['气血'] * 1.5)
        player_init_hp = player1['气血']
    else:
        player1['气血'] = int(player1['exp']/2*(1+user1_main_buff_data['hpbuff']/100+impart_data['impart_hp_per']/100))
        # 根据20241008汐汐酱PVE战斗记录，PVE时玩家血量有1.5倍buff
        player1['气血'] = int(player1['气血'] * 1.5)
        player_init_hp = player1['气血']
    if player1['真元'] == 0:
        player1['真元'] = int(player1['exp']*(1+user1_main_buff_data['mpbuff']/100+impart_data['impart_mp_per']/100))
    # 根据20241008汐汐酱PVE战斗记录，PVE时玩家攻击有2倍buff
    if player1['攻击'] != 0:
        player1['攻击'] = int(player1['攻击'] * 2)

    suc = None
    user1_turn_skip = True
    boss_turn_skip = True
    player1_turn_cost = 0  # 先设定为初始值 0
    player1_f_js = get_user_def_buff(player1)
    player1_js = player1_f_js # 减伤率
    
    global boss_zs
    global boss_hx
    global boss_bs 
    global boss_xx
    global boss_jg
    global boss_jh
    global boss_jb 
    global boss_xl
                
    if boss["jj"]==1: #convert_rank('真仙境初期')[0] < convert_rank((boss["jj"] + '中期'))[0] < convert_rank('遁一境圆满')[0]: #至尊境
            boss["减伤"] = random.randint(40,45) / 100 # boss减伤率
            boss_st1 = random.randint(0,100) #boss神通1
            if 0 <= boss_st1 <= 25:
                boss_zs = 0.4   #boss攻击
                boss_hx = 0
                boss_bs = 0
                boss_xx = 0
            elif 26 <= boss_st1 <= 50:
                boss_zs = 0
                boss_hx = 0.2   #boss会心
                boss_bs = 0
                boss_xx = 0
            elif 51 <= boss_st1 <= 75:
                boss_zs = 0
                boss_hx = 0
                boss_bs = 0.7   #boss暴伤
                boss_xx = 0
            elif 75 <= boss_st1 <= 100:
                boss_zs = 0
                boss_hx = 0
                boss_bs = 0
                boss_xx = random.randint(10,100) / 100  #boss禁血
                
            boss_st2 = random.randint(0,100) #boss神通2
            if 0 <= boss_st2 <= 25:
                boss_jg = 0.4   #boss降攻
                boss_jh = 0
                boss_jb = 0
                boss_xl = 0
            elif 26 <= boss_st2 <= 50:
                boss_jg = 0
                boss_jh = 0.4   #boss降会
                boss_jb = 0
                boss_xl = 0
            elif 51 <= boss_st2 <= 75:
                boss_jg = 0
                boss_jh = 0
                boss_jb = 0.7   #boss降暴
                boss_xl = 0
            elif 76 <= boss_st2 <= 100:
                boss_jg = 0
                boss_jh = 0
                boss_jb = 0
                boss_xl = random.randint(10,100) / 100  #boss禁蓝
    elif boss["jj"]==2: 
            boss["减伤"] = random.randint(20,25) / 100 # boss减伤率
            boss_st1 = random.randint(0,100) #boss神通1
            if 0 <= boss_st1 <= 25:
                boss_zs = 0.7   #boss攻击
                boss_hx = 0
                boss_bs = 0
                boss_xx = 0
            elif 26 <= boss_st1 <= 50:
                boss_zs = 0
                boss_hx = 0.45   #boss会心
                boss_bs = 0
                boss_xx = 0
            elif 51 <= boss_st1 <= 75:
                boss_zs = 0
                boss_hx = 0
                boss_bs = 1.3   #boss暴伤
                boss_xx = 0
            elif 75 <= boss_st1 <= 100:
                boss_zs = 0
                boss_hx = 0
                boss_bs = 0
                boss_xx = random.randint(40,100) / 100  #boss禁血
                
            boss_st2 = random.randint(0,100) #boss神通2
            if 0 <= boss_st2 <= 25:
                boss_jg = 0.55   #boss降攻
                boss_jh = 0
                boss_jb = 0
                boss_xl = 0
            elif 26 <= boss_st2 <= 50:
                boss_jg = 0
                boss_jh = 0.6   #boss降会
                boss_jb = 0
                boss_xl = 0
            elif 51 <= boss_st2 <= 75:
                boss_jg = 0
                boss_jh = 0
                boss_jb = 1   #boss降暴
                boss_xl = 0
            elif 76 <= boss_st2 <= 100:
                boss_jg = 0
                boss_jh = 0
                boss_jb = 0
                boss_xl = random.randint(40,100) / 100  #boss禁蓝  
    elif boss["jj"]==3: 
            # 待修正数值
            boss["减伤"] = 0.05 # boss减伤率
            boss_st1 = random.randint(0,100) #boss神通1
            if 0 <= boss_st1 <= 25:
                boss_zs = 0.9   #boss攻击
                boss_hx = 0
                boss_bs = 0
                boss_xx = 0
            elif 26 <= boss_st1 <= 50:
                boss_zs = 0
                boss_hx = 0.6   #boss会心
                boss_bs = 0
                boss_xx = 0
            elif 51 <= boss_st1 <= 75:
                boss_zs = 0
                boss_hx = 0
                boss_bs = 1.7   #boss暴伤
                boss_xx = 0
            elif 75 <= boss_st1 <= 100:
                boss_zs = 0
                boss_hx = 0
                boss_bs = 0
                boss_xx = random.randint(60,100) / 100  #boss禁血
                
            boss_st2 = random.randint(0,100) #boss神通2
            if 0 <= boss_st2 <= 25:
                boss_jg = 0.62   #boss降攻
                boss_jh = 0
                boss_jb = 0
                boss_xl = 0
            elif 26 <= boss_st2 <= 50:
                boss_jg = 0
                boss_jh = 0.67   #boss降会
                boss_jb = 0
                boss_xl = 0
            elif 51 <= boss_st2 <= 75:
                boss_jg = 0
                boss_jh = 0
                boss_jb = 1.2   #boss降暴
                boss_xl = 0
            elif 76 <= boss_st2 <= 100:
                boss_jg = 0
                boss_jh = 0
                boss_jb = 0
                boss_xl = random.randint(60,100) / 100  #boss禁蓝       
    

    sh = 0
    qx = boss['气血']
    boss_js = boss['减伤']
    
    
    if boss_js <= 0.6:
        if boss['name'] in BOSSDEF:
            effect_name = BOSSDEF[boss['name']]
            boss_js_data = {"name": f"{boss['name']}",
                                     "content": f"{effect_name},获得了{int((1-boss_js)*100)}%减伤!"}
        else:
            boss_js_data = {"name": f"{boss['name']}",
                                     "content": f"{boss['name']}获得了{int((1-boss_js)*100)}%减伤!"}
            
        play_list.append(boss_js_data)
    
    if boss_zs > 0 :
        boss_zs_data = {"name": f"{boss['name']}",
                                     "content": f"{boss['name']}使用了真龙九变,提升了{int(boss_zs *100)}%攻击力!"}
        
        play_list.append(boss_zs_data)
        
    if boss_hx > 0  :
        boss_hx_data = {"name": f"{boss['name']}",
                                     "content": f"{boss['name']}使用了无瑕七绝剑,提升了{int(boss_hx *100)}%会心率!"}
        
        play_list.append(boss_hx_data)
    
    if boss_bs > 0 :
        boss_bs_data = {"name": f"{boss['name']}",
                                     "content": f"{boss['name']}使用了太乙剑诀,提升了{int(boss_bs *100)}%会心伤害!"}
        
        play_list.append(boss_bs_data)
        
    if boss_xx > 0 :
        boss_xx_data = {"name": f"{boss['name']}",
                                     "content": f"{boss['name']}使用了七煞灭魂聚血杀阵,降低了{player1['道号']}{int((boss_xx) *100)}%气血吸取!"}
        
        play_list.append(boss_xx_data)
        
    if boss_jg > 0 :
        boss_jg_data = {"name": f"{boss['name']}",
                                     "content": f"{boss['name']}使用了子午安息香,降低了{player1['道号']}{int((boss_jg) *100)}%伤害!"}
        
        play_list.append(boss_jg_data)
    
    if boss_jh > 0 :
        boss_jh_data = {"name": f"{boss['name']}",
                                     "content": f"{boss['name']}使用了玄冥剑气,降低了{player1['道号']}{int((boss_jh) *100)}%会心率!"}
        
        play_list.append(boss_jh_data)
        
    if boss_jb > 0 :
        boss_jb_data = {"name": f"{boss['name']}",
                                     "content": f"{boss['name']}使用了大德琉璃金刚身,降低了{player1['道号']}{int((boss_jb) *100)}%会心伤害!"}
        
        play_list.append(boss_jb_data)
        
    if boss_xl > 0 :
        boss_xl_data = {"name": f"{boss['name']}",
                                     "content": f"{boss['name']}使用了千煌锁灵阵,降低了{player1['道号']}{int((boss_xl) *100)}%真元吸取!"}
        
        play_list.append(boss_xl_data)
  
    boss['会心'] = 30
    
    # if fan_data == True :
    #     fan_data = {"name": f"{player1['道号']}",
    #                                  "content": f"{player1['道号']}发动了辅修功法反咒禁制，无效化了减益！"}}
    #     play_list.append(fan_data)

    turncount = 0
    turn_limit = limit_num
    while True:
        turncount += 1
        if turncount > turn_limit:
            play_list.append({"name": "Bot", "content": "天昏地暗！大能叫停！"})
            suc = "战斗超过20回合，未能战胜！"
            # return play_list, suc
            break
        msg1 = "{}发起攻击，造成了{}伤害\n"
        msg2 = "{}发起攻击，造成了{}伤害\n"
        
        msg = start_sub_buff_handle(player1_sub_open,user1_sub_buff_date,False,{})
        play_list.append(get_msg_dict(player1, player_init_hp, msg))

        player2_health_temp = boss['气血']
        if player1_skil_open:  # 是否开启技能
            if user1_turn_skip:  # 无需跳过回合
                turn_start_msg = f"☆------{player1['道号']}的回合------☆"
                play_list.append(get_msg_dict(player1, player_init_hp, turn_start_msg))
                user1hpconst, user1mpcost, user1skill_type, skillrate = get_skill_hp_mp_data(player1, user1_skill_date)
                if player1_turn_cost == 0:  # 没有持续性技能生效
                    player1_js = player1_f_js  # 没有持续性技能生效,减伤恢复
                    if isEnableUserSikll(player1, user1hpconst, user1mpcost, player1_turn_cost,
                                         skillrate):  # 满足技能要求，#此处为技能的第一次释放
                        skillmsg, user1_skill_sh, player1_turn_cost = get_skill_sh_data(player1, user1_skill_date, boss_js+user1_break)
                        if user1skill_type == 1:  # 直接伤害类技能
                            play_list.append(get_msg_dict(player1, player_init_hp, skillmsg))
                            player1 = calculate_skill_cost(player1, user1hpconst, user1mpcost)
                            boss['气血'] = boss['气血'] - user1_skill_sh #int(user1_skill_sh * (boss_js + user1_break))  # 玩家1的伤害 * boss的减伤
                            boss_hp_msg = f"{boss['name']}剩余血量{number_to(boss['气血'])}"
                            play_list.append(get_msg_dict(player1, player_init_hp, boss_hp_msg))
                            sh += user1_skill_sh

                        elif user1skill_type == 2:  # 持续性伤害技能
                            play_list.append(get_msg_dict(player1, player_init_hp, skillmsg))
                            player1 = calculate_skill_cost(player1, user1hpconst, user1mpcost)
                            boss['气血'] = boss['气血'] -  user1_skill_sh # int(user1_skill_sh * (0.2 + boss_js + user1_break))  # 玩家1的伤害 * 玩家2的减伤
                            # 根据汐汐20240914的战斗日志，DOT技能的伤害不用计算boss的减伤
                            # boss['气血'] = boss['气血'] - int(user1_skill_sh * (0.2 + 1 + user1_break))  # 玩家1的伤害 * 玩家2的减伤
                            # 根据汐汐20240922的战斗日志，DOT技能首回合的0.2加成消失
                            # boss['气血'] = boss['气血'] - int(user1_skill_sh * (boss_js + user1_break))  # 玩家1的伤害 * 玩家2的减伤
                            boss_hp_msg = f"{boss['name']}剩余血量{number_to(boss['气血'])}"
                            play_list.append(get_msg_dict(player1, player_init_hp, boss_hp_msg))
                            sh += user1_skill_sh

                        elif user1skill_type == 3:  # buff类技能
                            user1buff_type = user1_skill_date['bufftype']
                            user1buff_value = user1_skill_date['buffvalue']
                            if user1buff_type == 1:  # 攻击类buff
                                isCrit, player1_sh = get_turnatk(player1,user1buff_value)  # 判定是否暴击 辅修功法14
                                if isCrit:
                                    msg1 = "{}发起会心一击，造成了{}伤害\n"
                                else:
                                    msg1 = "{}发起攻击，造成了{}伤害\n"
                                player1 = calculate_skill_cost(player1, user1hpconst, user1mpcost)
                                play_list.append(get_msg_dict(player1, player_init_hp, skillmsg))
                                player1_atk_msg = msg1.format(player1['道号'], number_to(player1_sh * (boss_js + user1_break) * 0.75))
                                play_list.append(get_msg_dict(player1, player_init_hp, player1_atk_msg))
                                boss['气血'] = boss['气血'] - int(player1_sh * (boss_js + user1_break) * 0.75)  # 玩家1的伤害 * 玩家2的减伤
                                boss_hp_msg = f"{boss['name']}剩余血量{number_to(boss['气血'])}"
                                play_list.append(get_msg_dict(player1, player_init_hp, boss_hp_msg))
                                sh += player1_sh

                            elif user1buff_type == 2:  # 减伤类buff,需要在player2处判断
                                isCrit, player1_sh = get_turnatk(player1, 0)  # 判定是否暴击 辅修功法14
                                if isCrit:
                                    msg1 = "{}发起会心一击，造成了{}伤害\n"
                                else:
                                    msg1 = "{}发起攻击，造成了{}伤害\n"

                                player1 = calculate_skill_cost(player1, user1hpconst, user1mpcost)
                                play_list.append(get_msg_dict(player1, player_init_hp, skillmsg))
                                player1_atk_msg = msg1.format(player1['道号'], number_to(player1_sh * (boss_js + user1_break) * 0.75))
                                play_list.append(get_msg_dict(player1, player_init_hp, player1_atk_msg))
                                boss['气血'] = boss['气血'] - int(player1_sh * (boss_js + user1_break) * 0.75)  # 玩家1的伤害 * 玩家2的减伤
                                boss_hp_msg = f"{boss['name']}剩余血量{number_to(boss['气血'])}"
                                play_list.append(get_msg_dict(player1, player_init_hp, boss_hp_msg))
                                player1_js = player1_f_js - user1_skill_sh
                                sh += player1_sh

                        elif user1skill_type == 4:  # 封印类技能
                            play_list.append(get_msg_dict(player1, player_init_hp, skillmsg))
                            player1 = calculate_skill_cost(player1, user1hpconst, user1mpcost)

                            if user1_skill_sh:  # 命中
                                boss_turn_skip = False
                                bossbuffturn = False

                    else:  # 没放技能，打一拳
                        isCrit, player1_sh = get_turnatk(player1, 0)  # 判定是否暴击 辅修功法14
                        if isCrit:
                            msg1 = "{}发起会心一击，造成了{}伤害\n"
                        else:
                            msg1 = "{}发起攻击，造成了{}伤害\n"
                        player1_atk_msg = msg1.format(player1['道号'], number_to(player1_sh * (boss_js + user1_break) * 0.75))
                        play_list.append(get_msg_dict(player1, player_init_hp, player1_atk_msg))
                        boss['气血'] = boss['气血'] - int(player1_sh * (boss_js + user1_break) * 0.75)  # 玩家1的伤害 * 玩家2的减伤
                        boss_hp_msg = f"{boss['name']}剩余血量{number_to(boss['气血'])}"
                        play_list.append(get_msg_dict(player1, player_init_hp, boss_hp_msg))
                        sh += player1_sh

                else:  # 持续性技能判断,不是第一次
                    if user1skill_type == 2:  # 持续性伤害技能 
                        player1_turn_cost = player1_turn_cost - 1
                        skillmsg = get_persistent_skill_msg(player1['道号'], user1_skill_date['name'], user1_skill_sh,
                                                            player1_turn_cost)
                        play_list.append(get_msg_dict(player1, player_init_hp, skillmsg))
                        isCrit, player1_sh = get_turnatk(player1, 0)  # 判定是否暴击 辅修功法14
                        if isCrit:
                            msg1 = "{}发起会心一击，造成了{}伤害\n"
                        else:
                            msg1 = "{}发起攻击，造成了{}伤害\n"
                        player1_atk_msg = msg1.format(player1['道号'], number_to(user1_skill_sh + player1_sh * (boss_js + user1_break) * 0.75))#player1_sh)
                        play_list.append(get_msg_dict(player1, player_init_hp, player1_atk_msg))
                        # 原版计算公式
                        # boss['气血'] = boss['气血'] - int((user1_skill_sh + player1_sh) * (boss_js + user1_break))
                        # 根据汐汐20240914的战斗日志，DOT技能的伤害不用计算boss的减伤
                        boss['气血'] = boss['气血'] - int(user1_skill_sh + player1_sh * (boss_js + user1_break) * 0.75)
                        boss_hp_msg = f"{boss['name']}剩余血量{number_to(boss['气血'])}"
                        play_list.append(get_msg_dict(player1, player_init_hp, boss_hp_msg))
                        sh += player1_sh + user1_skill_sh

                    elif user1skill_type == 3:  # buff类技能
                        user1buff_type = user1_skill_date['bufftype']
                        user1buff_value = user1_skill_date['buffvalue']
                        if user1buff_type == 1:  # 攻击类buff
                            # isCrit, player1_sh = get_turnatk(player1, user1_skill_sh)  # 判定是否暴击 辅修功法14
                            # 没看懂，改掉了
                            isCrit, player1_sh = get_turnatk(player1, user1buff_value)  # 判定是否暴击 辅修功法14
                            if isCrit:
                                msg1 = "{}发起会心一击，造成了{}伤害\n"
                            else:
                                msg1 = "{}发起攻击，造成了{}伤害\n"
                            player1_turn_cost = player1_turn_cost - 1
                            play_list.append(get_msg_dict(player1, player_init_hp,
                                                          f"{user1_skill_date['name']}增伤剩余:{player1_turn_cost}回合"))
                            player1_atk_msg = msg1.format(player1['道号'], number_to(player1_sh * (boss_js + user1_break) * 0.75))
                            play_list.append(get_msg_dict(player1, player_init_hp, player1_atk_msg))
                            boss['气血'] = boss['气血'] - int(player1_sh * (boss_js + user1_break) * 0.75)  # 玩家1的伤害 * 玩家2的减伤
                            boss_hp_msg = f"{boss['name']}剩余血量{number_to(boss['气血'])}"
                            play_list.append(get_msg_dict(player1, player_init_hp, boss_hp_msg))
                            sh += player1_sh

                        elif user1buff_type == 2:  # 减伤类buff,需要在player2处判断
                            isCrit, player1_sh = get_turnatk(player1, 0)  # 判定是否暴击 辅修功法14
                            if isCrit:
                                msg1 = "{}发起会心一击，造成了{}伤害\n"
                            else:
                                msg1 = "{}发起攻击，造成了{}伤害\n"

                            player1_turn_cost = player1_turn_cost - 1
                            play_list.append(get_msg_dict(player1, player_init_hp, f"减伤剩余{player1_turn_cost}回合！"))
                            player1_atk_msg = msg1.format(player1['道号'], number_to(player1_sh * (boss_js + user1_break) * 0.75))
                            play_list.append(get_msg_dict(player1, player_init_hp, player1_atk_msg))
                            boss['气血'] = boss['气血'] - int(player1_sh * (boss_js + user1_break) * 0.75)  # 玩家1的伤害 * 玩家2的减伤
                            boss_hp_msg = f"{boss['name']}剩余血量{number_to(boss['气血'])}" 
                            play_list.append(get_msg_dict(player1, player_init_hp, boss_hp_msg))
                            player1_js = player1_f_js - user1_skill_sh
                            sh += player1_sh

                    elif user1skill_type == 4:  # 封印类技能
                        player1_turn_cost = player1_turn_cost - 1
                        isCrit, player1_sh = get_turnatk(player1, 0)  # 判定是否暴击 辅修功法14
                        if isCrit:
                            msg1 = "{}发起会心一击，造成了{}伤害\n"
                        else:
                            msg1 = "{}发起攻击，造成了{}伤害\n"
                        skillmsg = get_persistent_skill_msg(player1['道号'], user1_skill_date['name'], user1_skill_sh,
                                                            player1_turn_cost)
                        play_list.append(get_msg_dict(player1, player_init_hp, skillmsg))
                        player1_atk_msg = msg1.format(player1['道号'], number_to(player1_sh))
                        play_list.append(get_msg_dict(player1, player_init_hp, player1_atk_msg))
                        boss['气血'] = boss['气血'] - int(player1_sh * (boss_js + user1_break) * 0.75)  # 玩家1的伤害 * 玩家2的减伤
                        boss_hp_msg = f"{boss['name']}剩余血量{number_to(boss['气血'])}"
                        play_list.append(get_msg_dict(player1, player_init_hp, boss_hp_msg))
                        sh += player1_sh
                        if player1_turn_cost == 0:  # 封印时间到
                            boss_turn_skip = True

            else:  # 休息回合-1
                play_list.append(get_msg_dict(player1, player_init_hp, f"☆------{player1['道号']}动弹不得！------☆"))
                if player1_turn_cost > 0:
                    player1_turn_cost -= 1
                if player1_turn_cost == 0:
                    user1_turn_skip = True

        else:  # 没有技能的derB
            play_list.append(get_msg_dict(player1, player_init_hp, f"☆------{player1['道号']}的回合------☆"))
            isCrit, player1_sh = get_turnatk(player1, 0)  # 判定是否暴击 辅修功法14
            if isCrit:
                msg1 = "{}发起会心一击，造成了{}伤害\n"
            else:
                msg1 = "{}发起攻击，造成了{}伤害\n"
            player1_atk_msg = msg1.format(player1['道号'], number_to(player1_sh * (boss_js + user1_break) * 0.75))
            play_list.append(get_msg_dict(player1, player_init_hp, player1_atk_msg))
            boss['气血'] = boss['气血'] - int(player1_sh * (boss_js + user1_break) * 0.75)  # 玩家1的伤害 * 玩家2的减伤
            boss_hp_msg = f"{boss['name']}剩余血量{number_to(boss['气血'])}"
            play_list.append(get_msg_dict(player1, player_init_hp, boss_hp_msg))
            sh += player1_sh
            
        ## 自己回合结束 处理 辅修功法14
        player1,boss,msg = after_atk_sub_buff_handle(player1_sub_open,player1,user1_main_buff_data,user1_sub_buff_date,player2_health_temp - boss['气血'],boss)
        play_list.append(get_msg_dict(player1, player_init_hp, msg))
        sh += player2_health_temp - boss['气血']

        if boss['气血'] <= 0:  # boss气血小于0，结算
            play_list.append(
                {"name": "Bot", "content": f"{player1['道号']}胜利"})
            suc = "群友赢了"
            break

        if player1_turn_cost < 0:  # 休息为负数，如果休息，则跳过回合，正常是0
            user1_turn_skip = False
            player1_turn_cost += 1

            # 没有技能的derB
        if boss_turn_skip:
            boss_sub = random.randint(0,100)
            if boss_sub <= 8:
                play_list.append(get_boss_dict(boss, qx, f"☆------{boss['name']}的回合------☆"))
                isCrit, boss_sh = get_turnatk_boss(boss,0)  # 判定是否暴击 辅修功法14
                if isCrit:
                    msg2 = "{}：紫玄掌！并会心造成了{}伤害\n"
                else:
                    msg2 = "{}：紫玄掌！造成了{}伤害\n"
                boss_skill_dmg = int(boss_sh * (1 + boss_zs) * 5 * 0.75 + (player1['气血'] * 0.3))
                boss_skill_dmg_def = int(boss_skill_dmg * (player1_js - random_def)) # (boss_sh * (1 + boss_zs) * (player1_js - random_def) * 5) + (player1['气血'] * 0.3)
                play_list.append(get_boss_dict(boss, qx, msg2.format(boss['name'], number_to(boss_skill_dmg_def))))
                player1['气血'] = player1['气血'] - boss_skill_dmg_def
                play_list.append(get_boss_dict(boss, qx, f"{player1['道号']}剩余血量{number_to(player1['气血'])}"))
            
            elif 8<= boss_sub <= 16:
                 play_list.append(get_boss_dict(boss, qx, f"☆------{boss['name']}的回合------☆"))
                 isCrit, boss_sh = get_turnatk_boss(boss,0)  # 判定是否暴击 辅修功法14
                 if isCrit:
                     msg2 = "{}：穿透护甲！并会心造成了{}伤害\n"
                 else:
                     msg2 = "{}：穿透了护甲！造成了{}伤害\n"
                 boss_break_dmg = int(boss_sh * (1 + boss_zs) * (player1_js - random_def + 0.5)  * 3 * 0.75)
                 play_list.append(get_boss_dict(boss, qx, msg2.format(boss['name'], number_to(boss_break_dmg))))
                 player1['气血'] = player1['气血'] - boss_break_dmg
                 play_list.append(get_boss_dict(boss, qx, f"{player1['道号']}剩余血量{number_to(player1['气血'])}"))
                
            else:
                play_list.append(get_boss_dict(boss, qx, f"☆------{boss['name']}的回合------☆"))
                isCrit, boss_sh = get_turnatk_boss(boss,0)  # 判定是否暴击 辅修功法14
                if isCrit:
                    msg2 = "{}发起会心一击，造成了{}伤害\n"
                else:
                    msg2 = "{}发起攻击，造成了{}伤害\n"
                boss_atk_dmg = int(boss_sh * (1 + boss_zs) * (player1_js - random_def) * 0.75)
                play_list.append(get_boss_dict(boss, qx, msg2.format(boss['name'], number_to(boss_atk_dmg))))
                player1['气血'] = player1['气血'] - boss_atk_dmg
                play_list.append(get_boss_dict(boss, qx, f"{player1['道号']}剩余血量{number_to(player1['气血'])}"))

        else:
            play_list.append(get_boss_dict(boss, qx, f"☆------{boss['name']}动弹不得！------☆"))

        if player1['气血'] <= 0:  # 玩家2气血小于0
            play_list.append(
                {"name": "Bot", "content": f"{boss['name']}胜利"})
            suc = "Boss赢了"

            # zx = boss['总血量']
            # boss['stone'] = 0
            break

        if player1['气血'] <= 0 or boss['气血'] <= 0:
            play_list.append({"name": "Bot", "content": "逻辑错误！"})
            break

    return play_list, suc#, boss


def get_msg_dict(player, player_init_hp, msg):
    # 简化输出
    # return {"name": f"{player['道号']}，当前血量：{int(player['气血'])} / {int(player_init_hp)}",
    #                                  "uin": int(player['user_id']), "content": msg}}
    return {"name": f"{player['道号']}，当前血量：{int(player['气血'])} / {int(player_init_hp)}",
                                    "content": msg}


def get_boss_dict(boss, boss_init_hp, msg):
    # 简化输出
    # return {"type": "node",
    #         "data": {"name": f"{boss['name']}当前血量：{int(boss['气血'])} / {int(boss_init_hp)}",
    #                  "content": msg}}
    return {"name": f"{boss['name']}当前血量：{int(boss['气血'])} / {int(boss_init_hp)}",
                     "content": msg}


def get_user_def_buff(player1):
    # user_armor_data = UserBuffDate(user_id).get_user_armor_buff_data()
    # user_weapon_data = UserBuffDate(user_id).get_user_weapon_data() #武器减伤
    # user_main_data = UserBuffDate(user_id).get_user_main_buff_data() #功法减伤
    if player1['武器加防'] is not None:
        weapon_def =  player1['武器加防']  #武器减伤
    else:
        weapon_def =0
    if player1['主功法防御buff'] is not None:
        main_def =  player1['主功法防御buff']  #功法减伤
    else:
        main_def =0
    if player1['防具加防'] is not None:
        def_buff = player1['防具加防']  #减伤公式
    else:
        def_buff = 0
    return round(1 - (def_buff + weapon_def + main_def )/100, 2)  # 初始减伤率

def get_turnatk(player, buff=0):
    sub_atk = 0
    sub_crit = 0
    sub_dmg = 0
    zwsh =0
    try:
        # user_id = player['user_id']
        # impart_data = None#xiuxian_impart.get_user_info_with_id(user_id)
        # user_buff_data = UserBuffDate(user_id)
        # weapon_critatk_data = player['武器加爆伤'] #武器会心伤害
        # 专武判定，默认没有，直接给0
        # weapon_zw = UserBuffDate(user_id).get_user_weapon_data()
        # main_zw = user_buff_data.get_user_main_buff_data()
        # if main_zw["ew"] == weapon_zw["zw"] :
        #     zwsh = 0.5
        # else:
        #     zwsh =0

        # main_critatk_data = player['主功法爆伤buff'] #功法会心伤害
        # user_sub_buff_date = {}
        # if user_buff_data.get_user_sub_buff_data() != None:
        #     user_sub_buff_date = UserBuffDate(user_id).get_user_sub_buff_data()
        buff_value = player['辅修buff数值'] if player['辅修buff数值'] is not None else 0
        buff_type = player['辅修buff类型'] if player['辅修buff类型'] is not None else 0
        if buff_type == "1":
            sub_atk = buff_value / 100
        else:
            sub_atk = 0
        if buff_type == "2":
            sub_crit = buff_value / 100
        else:
            sub_crit = 0
        if buff_type == "3":
            sub_dmg = buff_value / 100
        else:
            sub_dmg = 0
    except:
        # impart_data = None
        # weapon_critatk_data = None
        # main_critatk_data = None
        sub_atk = 0
        sub_crit = 0
        sub_dmg = 0
    impart_know_per = player['传承提升会'] if player['传承提升会'] is not None else 0
    impart_burst_per = player['传承提升爆'] if player['传承提升爆'] is not None else 0
    weapon_critatk = player['武器加爆伤'] if player['武器加爆伤'] is not None else 0 #武器会心伤害
    main_critatk = player['主功法爆伤buff'] if player['主功法爆伤buff'] is not None else 0 #功法会心伤害
    isCrit = False
    turnatk = int(round(random.uniform(0.95, 1.05), 2) 
                  * (player['攻击'] *  (buff + sub_atk + 1) * (1 - boss_jg)) * (1 + zwsh))  # 攻击波动,buff是攻击buff
    if random.randint(0, 100) <= player['会心'] + (impart_know_per + sub_crit - boss_jh + random_hx )* 100:  # 会心判断
        turnatk = int(turnatk * (1.5 + impart_burst_per + weapon_critatk + main_critatk + sub_dmg - boss_jb)) #boss战、切磋、秘境战斗会心伤害公式（不包含抢劫）
        isCrit = True
    return isCrit, turnatk

def get_turnatk_boss(player, buff=0): #boss伤害计算公式
    isCrit = False
    turnatk = int(round(random.uniform(0.95, 1.05), 2) 
                  * (player['攻击'] *  (buff  + 1)))  # 攻击波动,buff是攻击buff
    if random.randint(0, 100) <= player['会心'] + boss_hx * 100:  # 会心判断
        turnatk = int(turnatk * (1.5 + boss_bs )) #boss战、切磋、秘境战斗会心伤害公式（不包含抢劫）
        isCrit = True
    return isCrit, turnatk

def isEnableUserSikll(player, hpcost, mpcost, turncost, skillrate):  # 是否满足技能释放条件
    skill = False
    if turncost < 0:  # 判断是否进入休息状态
        return skill

    if player['气血'] > hpcost and player['真元'] >= mpcost:  # 判断血量、真元是否满足
        if random.randint(0, 100) <= skillrate:  # 随机概率释放技能
            skill = True
    return skill

def get_skill_hp_mp_data(player, secbuffdata):
    # user_id = player['user_id']
    # weapon_data = None #UserBuffDate(user_id).get_user_weapon_data()
    # if weapon_data is not None and "mp_buff" in weapon_data:
    #     weapon_mp = weapon_data["mp_buff"]
    # else:
    #     weapon_mp = 0
    weapon_mp = 0
    hpcost = int(secbuffdata['hpcost'] * player['气血']//100) if secbuffdata['hpcost'] != 0 else 0
    mpcost = int(secbuffdata['mpcost'] * player['exp'] * (1 - weapon_mp )//100) if secbuffdata['mpcost'] != 0 else 0
    return hpcost, mpcost, secbuffdata['skill_type'], secbuffdata['rate']


def calculate_skill_cost(player, hpcost, mpcost):
    player['气血'] = player['气血'] - hpcost  # 气血消耗
    player['真元'] = player['真元'] - mpcost  # 真元消耗
    return player


def get_persistent_skill_msg(username, skillname, sh, turn):
    if sh:
        return f"{username}的封印技能：{skillname}，剩余回合：{turn}!"
    return f"{username}的持续性技能：{skillname}，造成{number_to(sh)}伤害，剩余回合：{turn}!"


def get_skill_sh_data(player, secbuffdata, multiplier1):
    skillmsg = ''
    if secbuffdata['skill_type'] == 1:  # 连续攻击类型
        multiplier2 = 0.75
        turncost = -secbuffdata['turncost']
        isCrit, turnatk = get_turnatk(player, 0)
        atkvalue = secbuffdata['atkvalue']  # 列表
        skillsh = 0
        atkmsg = ''
        for value in atkvalue:
            atkmsg += f"{number_to(value * turnatk * multiplier1 * multiplier2)}伤害、"
            skillsh += int(value * turnatk* multiplier1 * multiplier2)

        if turncost == 0:
            turnmsg = '!'
        else:
            turnmsg = f"，休息{secbuffdata['turncost']}回合！"

        if isCrit:
            skillmsg = f"{player['道号']}发动技能：{secbuffdata['name']}，消耗气血{number_to(secbuffdata['hpcost'] * player['气血']//100) if secbuffdata['hpcost'] != 0 else 0}点、真元{number_to(secbuffdata['mpcost'] * player['exp']//100) if secbuffdata['mpcost'] != 0 else 0}点，{secbuffdata['desc']}并且发生了会心一击，造成{atkmsg[:-1]}{turnmsg}"
        else:
            skillmsg = f"{player['道号']}发动技能：{secbuffdata['name']}，消耗气血{number_to(secbuffdata['hpcost'] * player['气血']//100) if secbuffdata['hpcost'] != 0 else 0}点、真元{number_to(secbuffdata['mpcost'] * player['exp']//100) if secbuffdata['mpcost'] != 0 else 0}点，{secbuffdata['desc']}造成{atkmsg[:-1]}{turnmsg}"

        return skillmsg, skillsh, turncost

    elif secbuffdata['skill_type'] == 2:  # 持续伤害类型
        multiplier2 = 1
        turncost = secbuffdata['turncost']
        isCrit, turnatk = get_turnatk(player, 0)
        skillsh = int(secbuffdata['atkvalue'] * player['攻击']* multiplier1 * multiplier2)  # 改动
        atkmsg = ''
        if isCrit:
            skillmsg = f"{player['道号']}发动技能：{secbuffdata['name']}，消耗气血{number_to(secbuffdata['hpcost'] * player['气血']//100) if secbuffdata['hpcost'] != 0 else 0}点、真元{number_to(secbuffdata['mpcost'] * player['exp']//100) if secbuffdata['mpcost'] != 0 else 0}点，{secbuffdata['desc']}并且发生了会心一击，造成{number_to(skillsh)}点伤害，持续{turncost}回合！"
        else:
            skillmsg = f"{player['道号']}发动技能：{secbuffdata['name']}，消耗气血{number_to(secbuffdata['hpcost'] * player['气血']//100) if secbuffdata['hpcost'] != 0 else 0}点、真元{number_to(secbuffdata['mpcost'] * player['exp']//100) if secbuffdata['mpcost'] != 0 else 0}点，{secbuffdata['desc']}造成{number_to(skillsh)}点伤害，持续{turncost}回合！"

        return skillmsg, skillsh, turncost

    elif secbuffdata['skill_type'] == 3:  # 持续buff类型
        turncost = secbuffdata['turncost']
        skillsh = secbuffdata['buffvalue']
        atkmsg = ''
        if secbuffdata['bufftype'] == 1:
            skillmsg = f"{player['道号']}发动技能：{secbuffdata['name']}，消耗气血{number_to(secbuffdata['hpcost'] * player['气血'])/100 if secbuffdata['hpcost'] != 0 else 0}点、真元{number_to(secbuffdata['mpcost'] * player['exp']) if secbuffdata['mpcost'] != 0 else 0}点，{secbuffdata['desc']}攻击力增加{skillsh}倍，持续{turncost}回合！"
        elif secbuffdata['bufftype'] == 2:
            skillmsg = f"{player['道号']}发动技能：{secbuffdata['name']}，消耗气血{number_to(secbuffdata['hpcost'] * player['气血'])/100 if secbuffdata['hpcost'] != 0 else 0}点、真元{number_to(secbuffdata['mpcost'] * player['exp']) if secbuffdata['mpcost'] != 0 else 0}点，{secbuffdata['desc']}获得{skillsh * 100}%的减伤，持续{turncost}回合！"

        return skillmsg, skillsh, turncost

    elif secbuffdata['skill_type'] == 4:  # 封印类技能
        turncost = secbuffdata['turncost']
        if random.randint(0, 100) <= secbuffdata['success']:  # 命中
            skillsh = True
            skillmsg = f"{player['道号']}发动技能：{secbuffdata['name']}，消耗气血{number_to(secbuffdata['hpcost'] * player['气血']//100) if secbuffdata['hpcost'] != 0 else 0}点、真元{number_to(secbuffdata['mpcost'] * player['exp']//100) if secbuffdata['mpcost'] != 0 else 0}点，使对手动弹不得,{secbuffdata['desc']}持续{turncost}回合！"
        else:  # 未命中
            skillsh = False
            skillmsg = f"{player['道号']}发动技能：{secbuffdata['name']}，消耗气血{number_to(secbuffdata['hpcost'] * player['气血']//100) if secbuffdata['hpcost'] != 0 else 0}点、真元{number_to(secbuffdata['mpcost'] * player['exp']//100) if secbuffdata['mpcost'] != 0 else 0}点，{secbuffdata['desc']}但是被对手躲避！"

        return skillmsg, skillsh, turncost


# 处理开局的辅修功法效果
def apply_buff(subbuffdata, is_opponent=False):
    buff_type_to_attr = {
        '1': ('atk_buff', "攻击力"),
        '2': ('crit_buff', "暴击率"),
        '3': ('crit_dmg_buff', "暴击伤害"),
        '4': ('health_restore_buff', "气血回复"),
        '5': ('mana_restore_buff', "真元回复"),
        '6': ('health_stolen_buff', "气血吸取"),
        '7': ('mana_stolen_buff', "真元吸取"),
        '8': ('thorns_buff', "中毒"),
        '9': ('hm_stolen_buff', "气血真元吸取"),
        '10': ('jx_buff', "重伤效果"),
    }
    attr, desc = buff_type_to_attr[str(subbuffdata['buff_type'])]
    # setattr(user_battle_buff, attr, subbuffdata['buff'])
    if int(subbuffdata['buff_type']) >= 0 and int(subbuffdata['buff_type']) <= 10:
        sub_msg = f"提升{subbuffdata['buff']}%{desc}"
    else:
        sub_msg = "获得了特殊效果！！"
    prefix = "。对手" if is_opponent else ""
    return f"{prefix}使用功法{subbuffdata['name']}, {sub_msg}"


def start_sub_buff_handle(player1_sub_open, subbuffdata1,
                          player2_sub_open, subbuffdata2):
    msg1 = apply_buff(subbuffdata1, is_opponent=False) if player1_sub_open else ""
    msg2 = apply_buff(subbuffdata2, is_opponent=True) if player2_sub_open else ""

    return msg1 + msg2


# 处理攻击后辅修功法效果
def after_atk_sub_buff_handle(player1_sub_open, player1, user1_main_buff_data, subbuffdata1, damage1, player2):
    msg = ""

    if not player1_sub_open:
        return player1, player2, msg

    buff_value = int(subbuffdata1['buff'])
    buff_tow = int(subbuffdata1['buff2'])
    buff_type = subbuffdata1['buff_type']
    exp = int(player1['exp'])
    max_hp = int(exp / 2 * (1 + user1_main_buff_data['hpbuff']/100 if user1_main_buff_data is not None else 0))
    max_mp = int(exp * (1 + user1_main_buff_data['mpbuff']/100 if user1_main_buff_data is not None else 0))
    
    if buff_type == '4':
        restore_health = int(exp/2 * (1 + user1_main_buff_data['hpbuff']/100) * (buff_value/100))
        player1['气血'] += restore_health
        player1['气血'] = min(player1['气血'], max_hp)
        msg = "回复气血:" + str(number_to(restore_health))
    elif buff_type == '5':
        restore_mana = exp * (1 + user1_main_buff_data['mpbuff']/100) * (buff_value/100)
        player1['真元'] += restore_mana
        player1['真元'] = min(player1['真元'], max_mp)
        msg = "回复真元:" + str(number_to(restore_mana))
    elif buff_type == '6':
        health_stolen = (damage1 * ((buff_value/100) + random_xx)) * (1 - boss_xx)
        player1['气血'] += health_stolen
        player1['气血'] = min(player1['气血'], max_hp)
        msg = "吸取气血:" + str(number_to(health_stolen))
    elif buff_type == '7':
        mana_stolen = (damage1 * (buff_value/100)) * (1 - boss_xl)
        player1['真元'] += mana_stolen
        player1['真元'] = min(player1['真元'], max_mp)
        msg = "吸取真元:" + str(number_to(mana_stolen))
    elif buff_type == '8':
        # poison_damage = player2['气血'] * (buff_value/100) 
        # 根据汐汐20240914的战斗日志，辅修中毒效果需要计算减伤
        poison_damage = player2['气血'] * (buff_value/100) * player2['减伤']
        player2['气血'] -= poison_damage
        msg = "对手中毒消耗血量:" + str(number_to(poison_damage))
        
    elif buff_type == '9':
        health_stolen = (damage1 * (buff_value + random_xx) // 100) * (1 - boss_xx)
        mana_stolen = (damage1 * buff_tow // 100) * (1 - boss_xl)
        player1['气血'] += health_stolen
        player1['气血'] = min(player1['气血'], max_hp)
        player1['真元'] += mana_stolen
        player1['真元'] = min(player1['真元'], max_mp)
        msg = f"吸取气血: {str(number_to(health_stolen))}, 吸取真元: {str(number_to(mana_stolen))}"

    return player1, player2, msg


# class UserBattleBuffDate: #辅修功法14
#     def __init__(self, user_id):
#         """用户战斗Buff数据"""
#         self.user_id = user_id
#         # 攻击buff
#         self.atk_buff = 0
#         # 攻击buff
#         self.atk_buff_time = -1

#         # 暴击率buff
#         self.crit_buff = 0
#         # 暴击率buff
#         self.crit_buff_time = -1

#         # 暴击伤害buff
#         self.crit_dmg_buff = 0
#         # 暴击伤害buff
#         self.crit_dmg__buff_time = -1

#         # 回血buff
#         self.health_restore_buff = 0
#         self.health_restore_buff_time = -1
#         # 回蓝buff
#         self.mana_restore_buff = 0
#         self.mana_restore_buff_time = -1

#         # 吸血buff
#         self.health_stolen_buff = 0
#         self.health_stolen_buff_time = -1
#         # 吸蓝buff
#         self.mana_stolen_buff = 0
#         self.mana_stolen_buff_time = -1
#         # 反伤buff
#         self.thorns_buff = 0
#         self.thorns_buff_time = -1

#         # 破甲buff
#         self.armor_break_buff = 0
#         self.armor_break_buff_time = -1




    # boss['name','jj','气血','攻击','减伤','会心']
    # player1['user_id','exp','道号','气血','真元','攻击','会心']